<template>
  <!-- 日期选择弹框 -->
  <uni-popup ref="datePopup" type="bottom">
    <view class="date-picker-modal">
      <view class="picker-header">
        <text class="picker-title">选择日期</text>
      </view>

      <view v-if="showLabel" class="date-input-row">
        <text class="date-label">变动时间</text>
      </view>

      <view class="date-range-picker">
        <view
          class="date-input"
          :class="{ active: activeInput === 'start' }"
          @click="setActiveInput('start')"
        >
          <text>{{ tempRange.start }}</text>
        </view>
        <text class="date-separator">-</text>
        <view
          class="date-input"
          :class="{ active: activeInput === 'end' }"
          @click="setActiveInput('end')"
        >
          <text>{{ tempRange.end }}</text>
        </view>
      </view>

      <!-- 年月日滚轮选择器 -->
      <picker-view
        class="picker-view"
        :value="pickerValue"
        @change="pickerChange"
        :indicator-style="indicatorStyle"
      >
        <picker-view-column>
          <view v-for="year in years" :key="year" class="picker-item">
            {{ year }}年
          </view>
        </picker-view-column>
        <picker-view-column>
          <view v-for="month in months" :key="month" class="picker-item">
            {{ month }}月
          </view>
        </picker-view-column>
        <picker-view-column>
          <view v-for="day in days" :key="day" class="picker-item">
            {{ day }}日
          </view>
        </picker-view-column>
      </picker-view>

      <view class="picker-footer">
        <view class="footer-btn reset-btn" @click="resetDate">重置</view>
        <view class="footer-btn confirm-btn" @click="confirmDate">确认</view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ start: "", end: "" }),
  },
  showLabel: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

// 弹框引用
const datePopup = ref(null);

// 对外暴露方法
const open = () => {
  // 默认聚焦开始，并同步滚轮
  activeInput.value = "start";
  tempRange.value = { ...props.modelValue };
  setPickerByDate(tempRange.value.start || getToday());
  datePopup.value?.open();
};
const close = () => datePopup.value?.close();
defineExpose({ open, close });

// 临时范围、激活输入框
const tempRange = ref({ start: "", end: "" });
const activeInput = ref("start");

// 年月日数据
const years = ref([]);
const months = ref([]);
const days = ref([]);
const pickerValue = ref([0, 0, 0]);
// 使用固定 px 单位，避免 rpx 转换导致的对齐偏差
const indicatorStyle = "height: 50px;";

// 初始化年月日
const initData = () => {
  const now = new Date();
  const currentYear = now.getFullYear();
  years.value = [];
  for (let y = currentYear - 5; y <= currentYear + 1; y++) years.value.push(y);
  months.value = Array.from({ length: 12 }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );
};

onMounted(() => {
  initData();
  // 初始根据父值设置滚轮
  const initTarget = props.modelValue.start || getToday();
  setPickerByDate(initTarget);
});

// 监听父级变更
watch(
  () => props.modelValue,
  (val) => {
    tempRange.value = { ...(val || {}) };
  },
  { immediate: true, deep: true }
);

// 切换激活输入框
const setActiveInput = (type) => {
  activeInput.value = type;
  const target = type === "start" ? tempRange.value.start : tempRange.value.end;
  setPickerByDate(target || getToday());
};

// 滚轮变化
const pickerChange = (e) => {
  const [yIdx, mIdx, dIdx] = e.detail.value;
  const year = years.value[yIdx];
  const month = Number(months.value[mIdx]);

  // 重建天数
  const numDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: numDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );
  const safeDayIdx = Math.min(dIdx, days.value.length - 1);
  pickerValue.value = [yIdx, mIdx, safeDayIdx];

  const picked = `${year}-${String(month).padStart(2, "0")}-${
    days.value[safeDayIdx]
  }`;
  if (activeInput.value === "start") {
    tempRange.value.start = picked;
    if (dateToTs(picked) > dateToTs(tempRange.value.end)) {
      tempRange.value.end = picked;
    }
  } else {
    if (dateToTs(picked) < dateToTs(tempRange.value.start)) {
      uni.showToast({ title: "结束时间不能小于开始时间", icon: "none" });
      tempRange.value.end = tempRange.value.start;
      setPickerByDate(tempRange.value.end);
      return;
    }
    tempRange.value.end = picked;
  }
};

// 将滚轮同步到指定日期
const setPickerByDate = (dateStr) => {
  const [yStr, mStr, dStr] = (dateStr || getToday()).split("-");
  const year = Number(yStr);
  const month = Number(mStr);
  const day = Number(dStr);

  const numDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: numDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );

  const yIdx = years.value.findIndex((y) => y === year);
  const mIdx = months.value.findIndex(
    (m) => m === String(month).padStart(2, "0")
  );
  const dIdx = Math.min(
    days.value.findIndex((d) => d === String(day).padStart(2, "0")),
    days.value.length - 1
  );
  if (yIdx !== -1 && mIdx !== -1 && dIdx !== -1)
    pickerValue.value = [yIdx, mIdx, dIdx];
};

// 重置与确认
const resetDate = () => {
  const end = getToday();
  const startDate = new Date(
    new Date(end).getTime() - 30 * 24 * 60 * 60 * 1000
  );
  const start = `${startDate.getFullYear()}-${String(
    startDate.getMonth() + 1
  ).padStart(2, "0")}-${String(startDate.getDate()).padStart(2, "0")}`;
  tempRange.value = { start, end };
  activeInput.value = "start";
  setPickerByDate(start);
};

const confirmDate = () => {
  emit("update:modelValue", { ...tempRange.value });
  emit("confirm", { ...tempRange.value });
  close();
};

// 工具：今天和时间戳
const getToday = () => {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(now.getDate()).padStart(2, "0")}`;
};

const dateToTs = (str) => {
  const [y, m, d] = str.split("-").map((n) => Number(n));
  return new Date(y, m - 1, d).getTime();
};
</script>

<style lang="scss" scoped>
.date-picker-modal {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.picker-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  text-align: center;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.date-input-row {
  padding: 24rpx 32rpx;
}

.date-label {
  font-size: 28rpx;
  color: #333;
}

.date-range-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx 24rpx;
  gap: 16rpx;
}

.date-input {
  flex: 1;
  padding: 20rpx;
  background-color: #f5f5f5;
  border: 2rpx solid transparent;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;

  &.active {
    border-color: #ff9500;
    background-color: #fff5e6;
  }
}

.date-separator {
  font-size: 28rpx;
  color: #999;
}

.picker-view {
  height: 400rpx;
  padding: 0 32rpx 16rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  /* 与 indicatorStyle 完全一致，避免选中行偏移 */
  height: 50px;
  line-height: 50px;
  font-size: 32rpx;
  color: #333;
}

.picker-footer {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f5f5f5;
}

.footer-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;

  &:active {
    opacity: 0.8;
  }
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(135deg, #ffd000 0%, #ff9500 100%);
  color: #fff;
  font-weight: 600;
}
</style>
